package com.hk.web.core.intercept;

import com.hk.base.constant.BaseConstant;
import com.hk.commons.utils.WebUtil;
import com.hk.dao.manage.user.model.ManagerUserDO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MonitorInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = LoggerFactory.getLogger(MonitorInterceptor.class);

    private NamedThreadLocal<Long> startDatetimeMSThreadLocal = new NamedThreadLocal<>("startMS");


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        startDatetimeMSThreadLocal.set(System.currentTimeMillis());
        if (request instanceof HttpServletRequest == false) {
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        long costMS = System.currentTimeMillis() - startDatetimeMSThreadLocal.get();
        saveAccessTrace(request, costMS);
    }

    /**
     * access trace log record
     *
     */
    private void saveAccessTrace(HttpServletRequest request, long visitCostMS) {
        String requestUrl = request.getRequestURL().toString();
        String visitorIP = WebUtil.getVisitorIP(request);
        ManagerUserDO user = getUser();
        String str;
        str = "未登录用户";
        if (null != user) {
            str = "用户：" + user.getUsername();
        }
        logger.info(str + "请求从IP：{}，访问地址：{}，耗时毫秒数：{}", visitorIP, requestUrl, visitCostMS);
    }

    private ManagerUserDO getUser() {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        if (null == session) {
            return null;
        }
        return (ManagerUserDO) session.getAttribute(BaseConstant.LOGIN_SESSION_USER);
    }


}
